import React from 'react';
import { useParams } from 'react-router-dom';
import {
  makeStyles,
  Card,
  Button,
  Text,
  Badge,
  Spinner,
  Tab,
  TabList,
  TabValue,
} from '@fluentui/react-components';
import {
  Edit20Regular,
  AlertBadge20Regular,
  DocumentBulletList20Regular,
  Timeline20Regular,
} from '@fluentui/react-icons';

const useStyles = makeStyles({
  container: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  title: {
    fontSize: '24px',
    fontWeight: '600',
    color: '#1D2129',
    margin: 0,
  },
  actions: {
    display: 'flex',
    gap: '12px',
  },
  mainContent: {
    display: 'grid',
    gridTemplateColumns: '1fr 300px',
    gap: '24px',
    '@media (max-width: 1024px)': {
      gridTemplateColumns: '1fr',
    },
  },
  leftColumn: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
  },
  rightColumn: {
    display: 'flex',
    flexDirection: 'column',
    gap: '24px',
  },
  basicInfo: {
    padding: '24px',
  },
  infoRow: {
    display: 'flex',
    marginBottom: '16px',
  },
  infoLabel: {
    width: '120px',
    fontSize: '14px',
    color: '#86909C',
    fontWeight: '500',
  },
  infoValue: {
    flex: 1,
    fontSize: '14px',
    color: '#1D2129',
  },
  progressCard: {
    padding: '24px',
  },
  progressTimeline: {
    position: 'relative',
    paddingLeft: '24px',
  },
  timelineItem: {
    position: 'relative',
    paddingBottom: '24px',
    '&:not(:last-child)::before': {
      content: '""',
      position: 'absolute',
      left: '-13px',
      top: '24px',
      width: '2px',
      height: 'calc(100% - 24px)',
      backgroundColor: '#E5E6EB',
    },
  },
  timelineDot: {
    position: 'absolute',
    left: '-20px',
    top: '4px',
    width: '12px',
    height: '12px',
    borderRadius: '50%',
    backgroundColor: '#165DFF',
    border: '2px solid #FFFFFF',
    boxShadow: '0 0 0 2px #E5E6EB',
  },
  timelineContent: {
    backgroundColor: '#F8F9FA',
    borderRadius: '8px',
    padding: '16px',
  },
  timelineDate: {
    fontSize: '12px',
    color: '#86909C',
    marginBottom: '8px',
  },
  timelineDescription: {
    fontSize: '14px',
    color: '#1D2129',
    marginBottom: '8px',
  },
  timelineOutcome: {
    fontSize: '13px',
    color: '#4E5969',
  },
  tabContent: {
    padding: '24px',
    minHeight: '400px',
  },
  loadingContainer: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '200px',
  },
  statusBadge: {
    fontSize: '12px',
  },
  valueDisplay: {
    fontSize: '20px',
    fontWeight: '600',
    color: '#165DFF',
  },
});

const OpportunityDetailPage: React.FC = () => {
  const classes = useStyles();
  const { id } = useParams<{ id: string }>();
  const [selectedTab, setSelectedTab] = React.useState<TabValue>('plan');
  const [loading, setLoading] = React.useState(true);
  const [opportunity, setOpportunity] = React.useState<any>(null);

  React.useEffect(() => {
    // 模拟数据加载
    const loadOpportunity = async () => {
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockOpportunity = {
        id: id,
        customerName: '阿里巴巴集团',
        opportunityName: '云计算数字化转型项目',
        value: 12000000,
        status: 'negotiation',
        expectedCloseDate: '2024-09-15',
        owner: '张三',
        industry: '互联网',
        description: '帮助阿里巴巴完成内部系统的云计算转型，包括基础设施升级、数据迁移、系统集成等服务。',
        probability: 75,
        createdAt: '2024-06-01T10:00:00Z',
        updatedAt: '2024-07-20T15:30:00Z',
        contact: {
          name: '李经理',
          phone: '13800138001',
          email: 'li@alibaba.com',
          position: '技术总监',
        },
        progress: [
          {
            id: '1',
            date: '2024-07-20T15:30:00Z',
            description: '与客户进行技术方案讨论',
            type: 'meeting',
            outcome: '客户对技术方案表示满意，要求提供详细的实施计划',
            nextAction: '准备详细的项目实施方案',
            createdBy: '张三',
          },
          {
            id: '2',
            date: '2024-07-15T10:20:00Z',
            description: '提交初步技术方案',
            type: 'proposal',
            outcome: '方案已提交，等待客户反馈',
            nextAction: '跟进客户反馈意见',
            createdBy: '张三',
          },
          {
            id: '3',
            date: '2024-07-10T14:45:00Z',
            description: '首次客户需求调研',
            type: 'meeting',
            outcome: '了解客户基本需求，确定项目范围',
            nextAction: '制定技术方案',
            createdBy: '张三',
          },
        ],
      };

      setOpportunity(mockOpportunity);
      setLoading(false);
    };

    loadOpportunity();
  }, [id]);

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const getStatusInfo = (status: string) => {
    const statusMap: any = {
      'initial': { label: '初步接触', color: '#FF7D00' },
      'communication': { label: '需求沟通', color: '#165DFF' },
      'proposal': { label: '方案制定', color: '#00B42A' },
      'negotiation': { label: '商务谈判', color: '#86909C' },
      'closed_won': { label: '已成单', color: '#00B42A' },
      'closed_lost': { label: '已关闭', color: '#F53F3F' },
    };
    return statusMap[status] || { label: status, color: '#86909C' };
  };

  if (loading) {
    return (
      <div className={classes.loadingContainer}>
        <Spinner size="large" label="加载中..." />
      </div>
    );
  }

  if (!opportunity) {
    return <div>商机不存在</div>;
  }

  const statusInfo = getStatusInfo(opportunity.status);

  return (
    <div className={classes.container}>
      {/* 页面头部 */}
      <div className={classes.header}>
        <div>
          <h1 className={classes.title}>{opportunity.opportunityName}</h1>
          <Text>{opportunity.customerName}</Text>
        </div>
        <div className={classes.actions}>
          <Button appearance="secondary" icon={<Edit20Regular />}>
            编辑
          </Button>
          <Button appearance="secondary" icon={<Timeline20Regular />}>
            提交进展
          </Button>
          <Button appearance="secondary" icon={<AlertBadge20Regular />}>
            上报风险
          </Button>
          <Button appearance="primary" icon={<DocumentBulletList20Regular />}>
            生成计划
          </Button>
        </div>
      </div>

      {/* 主要内容 */}
      <div className={classes.mainContent}>
        {/* 左侧内容 */}
        <div className={classes.leftColumn}>
          {/* 选项卡内容 */}
          <Card>
            <TabList selectedValue={selectedTab} onTabSelect={(_, data) => setSelectedTab(data.value)}>
              <Tab value="plan">商务计划</Tab>
              <Tab value="communication">沟通记录</Tab>
              <Tab value="files">相关文件</Tab>
              <Tab value="notes">备注信息</Tab>
            </TabList>
            
            <div className={classes.tabContent}>
              {selectedTab === 'plan' && (
                <div>
                  <Text weight="semibold" size={400}>AI生成的商务计划</Text>
                  <div style={{ marginTop: '16px', lineHeight: '1.6' }}>
                    <p>基于当前商机情况，建议采用以下跟进策略：</p>
                    <ul style={{ marginTop: '12px', paddingLeft: '20px' }}>
                      <li>每周进行一次技术方案讨论，确保项目进度</li>
                      <li>安排客户现场调研，深入了解具体需求</li>
                      <li>准备详细的ROI分析报告</li>
                      <li>邀请技术专家参与方案优化</li>
                    </ul>
                  </div>
                </div>
              )}
              
              {selectedTab === 'communication' && (
                <div>
                  <Text weight="semibold" size={400}>沟通历史记录</Text>
                  <div style={{ marginTop: '16px' }}>
                    <Text>暂无沟通记录</Text>
                  </div>
                </div>
              )}
              
              {selectedTab === 'files' && (
                <div>
                  <Text weight="semibold" size={400}>相关文件</Text>
                  <div style={{ marginTop: '16px' }}>
                    <Text>暂无文件</Text>
                  </div>
                </div>
              )}
              
              {selectedTab === 'notes' && (
                <div>
                  <Text weight="semibold" size={400}>备注信息</Text>
                  <div style={{ marginTop: '16px' }}>
                    <Text>暂无备注</Text>
                  </div>
                </div>
              )}
            </div>
          </Card>
        </div>

        {/* 右侧内容 */}
        <div className={classes.rightColumn}>
          {/* 基本信息 */}
          <Card className={classes.basicInfo}>
            <Text weight="semibold" size={500} style={{ marginBottom: '16px' }}>
              基本信息
            </Text>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>商机价值</div>
              <div className={`${classes.infoValue} ${classes.valueDisplay}`}>
                {formatCurrency(opportunity.value)}
              </div>
            </div>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>当前状态</div>
              <div className={classes.infoValue}>
                <Badge 
                  appearance="filled" 
                  style={{ backgroundColor: statusInfo.color, color: 'white' }}
                  className={classes.statusBadge}
                >
                  {statusInfo.label}
                </Badge>
              </div>
            </div>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>成单概率</div>
              <div className={classes.infoValue}>{opportunity.probability}%</div>
            </div>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>预计成单</div>
              <div className={classes.infoValue}>
                {new Date(opportunity.expectedCloseDate).toLocaleDateString('zh-CN')}
              </div>
            </div>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>负责人</div>
              <div className={classes.infoValue}>{opportunity.owner}</div>
            </div>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>行业</div>
              <div className={classes.infoValue}>{opportunity.industry}</div>
            </div>
            
            <div className={classes.infoRow}>
              <div className={classes.infoLabel}>联系人</div>
              <div className={classes.infoValue}>
                {opportunity.contact.name} ({opportunity.contact.position})
                <br />
                <Text size={200} style={{ color: '#86909C' }}>
                  {opportunity.contact.phone}
                  <br />
                  {opportunity.contact.email}
                </Text>
              </div>
            </div>
          </Card>

          {/* 进度跟踪 */}
          <Card className={classes.progressCard}>
            <Text weight="semibold" size={500} style={{ marginBottom: '16px' }}>
              进度跟踪
            </Text>
            
            <div className={classes.progressTimeline}>
              {opportunity.progress.map((item: any) => (
                <div key={item.id} className={classes.timelineItem}>
                  <div className={classes.timelineDot} />
                  <div className={classes.timelineContent}>
                    <div className={classes.timelineDate}>
                      {new Date(item.date).toLocaleString('zh-CN')} - {item.createdBy}
                    </div>
                    <div className={classes.timelineDescription}>
                      {item.description}
                    </div>
                    <div className={classes.timelineOutcome}>
                      {item.outcome}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default OpportunityDetailPage;
